package com.utils.basejava.concurrent.atguigu;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程操作资源类 判断干活通知 防止虚假唤醒
 * 
 * @author XR-8 用阻塞队列实现的生产者消费者,并不使用锁，阻塞这一过程交给阻塞队列去控制
 */
class BlockingQueueData {
	private volatile boolean state = false;
	private AtomicInteger atomicInteger = new AtomicInteger();
	private BlockingQueue<String> blockingQueue;

	public BlockingQueueData(BlockingQueue<String> blockingQueue) {
		this.blockingQueue = blockingQueue;
	}

	public void produce() throws InterruptedException {
		while (!state) {
			String data = atomicInteger.incrementAndGet() + "";
			boolean success = blockingQueue.offer(data, 2, TimeUnit.SECONDS);
			if (success) {
				System.out.println(Thread.currentThread().getName() + "\t" + "生产了第" + data + "个，成功");
			} else {
				System.out.println(Thread.currentThread().getName() + "\t" + "生产了第" + data + "个，失败");

			}

			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println(Thread.currentThread().getName() + "\t 停止生产，表示FLAG=false，生产介绍");

	}

	public void consumer() throws InterruptedException {
		while (!state) {
			String success = blockingQueue.poll(2, TimeUnit.SECONDS);
			if (success != null && !"".equals(success)) {
				System.out.println(Thread.currentThread().getName() + "\t" + "消费了第" + success + "个，成功");
			} else {
				state = true;
				System.out.println(Thread.currentThread().getName() + "\t" + "消费了第" + success + "个，失败");
				return;
			}
		}
	}

	public void stop() {
		state = true;
	}

}

public class ProductConsumeDemo2 {
	public static void main(String[] args) {
		BlockingQueueData blockingQueueData = new BlockingQueueData(new ArrayBlockingQueue<>(10));

		new Thread(() -> {
			System.out.println(Thread.currentThread().getName() + "\t" + "线程启动");
			try {
				blockingQueueData.produce();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}, "pro").start();

		new Thread(() -> {
			System.out.println(Thread.currentThread().getName() + "\t" + "线程启动");
			try {
				blockingQueueData.consumer();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}, "con").start();

		try {
			TimeUnit.SECONDS.sleep(5);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("5秒后，生产和消费线程停止，线程结束");
		blockingQueueData.stop();

	}
}
